package com.one.entity;

/**
 * 分页参数管理器
 */
public class PageManager {

    private int pn = 1;//当前页
    private int rn = 7;//每页显示数据条数
    private int totalCount;//总数据数
    private int pages;//总页数
    private int start;//起始数据条数

    public PageManager() {
    }

    public PageManager(int pn, int rn, int totalCount, int pages) {
        this.pn = pn;
        this.rn = rn;
        this.totalCount = totalCount;
        this.pages = pages;
    }

    public PageManager(int pn, int rn, int totalCount) {
        //rn不能为0
        this.rn = getDefRn(rn, this.rn);
        //计算总数据数
        this.totalCount = totalCount;
        //直接使用小数相除，如果小数点后有小数，证明最后一页不足rn。要+1页
        this.pages = calPages(totalCount, this.rn);
        //当前页小于1的，如果是0，证明出现了转化异常
        this.pn = getDefPn(pn);
        //计算start
    }

    public int getPn() {
        return pn;
    }

    public void setPn(int pn) {
        this.pn = pn;
    }

    public int getRn() {
        return rn;
    }

    public void setRn(int rn) {
        this.rn = rn;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public int getStart() {
        this.start = (this.pn - 1) * this.rn;
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    /**
     * 判断当前页如果是0，就默认第一页
     */
    public int getDefPn(int pn){
        return (pn <= 0) ? this.pn : ((pn > this.pages && this.pages != 0) ? this.pages : pn);
    }

    /**
     * 计算总页数
     * @param totalCount 总数据数
     * @param rn 每页显示数据条数
     */
    public int calPages(int totalCount, int rn){
        return (int) Math.ceil(totalCount / (double)rn);
    }

    /**
     * 如果每页显示数据条数是0，默认是5条
     */
    public int getDefRn(int rn, int defNum) {
        return (rn == 0) ? ((defNum == 0) ? this.rn : defNum) : rn;
    }

    @Override
    public String toString() {
        return "PageManager{" +
                "pn=" + pn +
                ", rn=" + rn +
                ", totalCount=" + totalCount +
                ", pages=" + pages +
                ", start=" + start +
                '}';
    }
}
